import { useEffect, useState } from 'react';
import { useUrlSearchParams } from 'use-url-search-params';
import an58 from '@mmstudio/an000058';
import RightContainer from '../../../components/rightcontainer';
import Search from '../../../components/search';
import Title from './title';
import List from './list';
import api from '../../../atoms/api';
import Pagination from '../../../components/pagination';
import Add from './add';
import { IData, Message as M1, Result as R1 } from '../../api/admin/role/query.api';

const queryapi = api['/api/admin/role/query'];

export default function Content({ initialquery, menus }: {
	initialquery: M1;
	menus: ITbfdmenu[];
}) {
	const [data, setdata] = useState<R1>({
		count: 0,
		data: []
	});
	const [query, setquery] = useState<M1>(initialquery);
	const [, setParams] = useUrlSearchParams({}, { page: Number });
	async function reload(q: M1) {
		setquery(q);
		setParams(q);
		const data = await an58<R1, M1>(queryapi, 'get', q);
		setdata(data);
	}
	useEffect(() => {
		void reload(query);
	}, []);

	return <>
		<Title />
		<RightContainer>
			<Search<IData>
				pagesize={Number(query.pagesize)}
				service={queryapi}
				initq={query.q}
				onChange={(v) => {
					setdata({
						count: v.count,
						data: v.data
					});
					setquery({
						q: v.q,
						page: v.page.toString(),
						pagesize: query.pagesize
					});
				}} />
			<Add />
		</RightContainer>
		<List data={data.data} menus={menus} />
		<RightContainer>
			<Pagination
				current={Number(query.page || '1')}
				pageSize={Number(query.pagesize || '10')}
				showTitle
				total={data.count}
				onChange={(p, s) => {
					const q = {
						q: query.q,
						page: p.toString(),
						pagesize: s.toString()
					} as M1;
					setquery(q);
					reload(q);
				}}
			/>
		</RightContainer>
	</>;
}
